﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.EFDBFirst;

namespace YiYiTong.Rocket.Api.Biz
{
    public class JingjiaService : ApiService
    {
        /// <summary>
        /// 获取当前的竞拍配置
        /// </summary>
        /// <param name="apiContext"></param>
        public void GetConfig(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            var jingjiaConfigModel = new JingjiaConfigModel();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ADZ_JingjiaConfig aDZ_JingjiaConfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.is_show == 1);
            if (aDZ_JingjiaConfig != null)
            {
                List<string> exceptList = new List<string>();
                Utils.Mapper(jingjiaConfigModel, aDZ_JingjiaConfig, exceptList);
                var master = (from t in dbcontext.ADZ_JingjiaMaster.Where(t => t.jingjia_config_id == jingjiaConfigModel.jingjia_config_id && t.is_del == 0)
                              group t by new { t.chujia_counts, t.weiguan_counts, t.jingjia_id } into b
                              select new
                              {
                                  chujia_counts = b.Sum(x => x.chujia_counts),
                                  weiguan_counts = b.Sum(x => x.weiguan_counts),
                                  package_counts = b.Count(x => x.jingjia_id > 0)
                              }).FirstOrDefault();
                if (master != null)
                {
                    jingjiaConfigModel.package_counts = master.package_counts;
                    jingjiaConfigModel.chujia_counts = master.chujia_counts;
                    jingjiaConfigModel.weiguan_counts = master.weiguan_counts;
                }
                //检查自己是否已经报名
                var baominginfo = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(t => t.jingjia_config_id == aDZ_JingjiaConfig.jingjia_config_id
                && t.uid == apiContext.CurrUserId && t.is_succ == 1);
                if (baominginfo != null)
                {
                    jingjiaConfigModel.is_baoming = 1;
                }

                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(jingjiaConfigModel);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "竞价信息为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }
        /// <summary>
        /// 竞价列表查询
        /// </summary>
        /// <returns></returns>
        public void GetList(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long jingjia_config_id = dic.GetValue<long>("jingjia_config_id", -10);        //竞价配置ID
            long brand_id = dic.GetValue<long>("brand_id", -10);        //品牌id
            long category_id = dic.GetValue<long>("category_id", -10);  //分类id
            string selKey = dic.GetValue<string>("selkey");             //搜索关键字
            int pageindex = dic.GetValue<int>("pageindex", 1);
            int pagerows = dic.GetValue<int>("pagerows", 10);

            Tuple<bool, JingjiaListModel> tupleResult = JingjiaBiz.Instance.GetList(jingjia_config_id, apiContext.CurrUserId, brand_id, category_id, selKey, pageindex, pagerows);
            if (tupleResult.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(tupleResult.Item2);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "竞价列表为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 获取竞价信息
        /// </summary>
        /// <param name="apiContext"></param>
        public void GetInfo(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long jingjia_id = dic.GetValue<int>("jingjia_id", -10);
            long uid = apiContext.CurrUserId;
            var tupleResult = JingjiaBiz.Instance.GetInfo(uid, jingjia_id);
            if (tupleResult.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(tupleResult.Item2);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "竞价信息为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 获取竞价商品列表
        /// </summary>
        /// <param name="apiContext"></param>
        public void GetGoodsList(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long jingjia_id = dic.GetValue<int>("jingjia_id", -10);
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            List<GoodsModel> list = (from t in dbcontext.Views_Goods.Where(v => v.is_del == 0)
                                     join s in dbcontext.ADZ_GoodsJingjia.Where(v => v.jingjia_id == jingjia_id)
                                     on t.goods_id equals s.goods_id
                                     select new GoodsModel()
                                     {
                                         MPN = t.MPN,
                                         goods_id = t.goods_id,
                                         brand_name = t.brand_name,
                                         category_name = t.category_name,
                                         supplier_name = t.supplier_name,
                                         DCN = t.DCN,
                                         stock_amount = t.stock_amount.Value,
                                         goods_unit = t.goods_unit
                                     }).ToList();

            GoodsListModel listModel = new GoodsListModel();
            listModel.allpages = 1;
            if (list.Any())
            {
                //赋值图片
                list.ForEach(t =>
                {
                    t.imglist = GoodsBiz.Instance.GetGoodsIMG(t.goods_id);
                    t.show_min_level = 0;
                });
                listModel.list = list;
                listModel.allrows = list.Count;

                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(listModel);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "商品为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 出价记录
        /// </summary>
        public void GetChujiaList(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long jingjia_id = dic.GetValue<int>("jingjia_id", -10);

            if (jingjia_id <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "缺少参数";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var aDZ_chujialist = (from t in dbcontext.ADZ_JingjiaSubmit.Where(v => v.jingjia_id == jingjia_id)
                                  join u in dbcontext.ADZ_MemberMaster
                                  on t.uid equals u.uid
                                  orderby t.seq_id descending
                                  select new JingjiaChujiaModel()
                                  {
                                      seq_id = t.seq_id,
                                      create_time = t.create_time,
                                      uid = t.uid,
                                      is_hit = t.is_hit,
                                      jingjia_id = t.jingjia_id,
                                      username = u.account_mobile,
                                      my_price = t.my_price,
                                      status = t.status
                                  }
                                     ).ToList();


            JingjiaChujiaListModel listModel = new JingjiaChujiaListModel();
            listModel.allpages = 1;
            if (aDZ_chujialist.Any())
            {
                aDZ_chujialist.ForEach(t =>
                {
                    t.username = Utils.ModifyMobile(t.username);

                    if (t.is_hit == 1)
                    {
                        t.order_station = 1;
                        t.status_msg = "成交";
                    }
                    else if (t.status == 0)
                    {
                        t.order_station = 2;
                        t.status_msg = "领先";
                    }
                    else
                    {
                        t.order_station = 3;
                        t.status_msg = "落后";
                    }
                });

                listModel.list = aDZ_chujialist;
                listModel.allrows = aDZ_chujialist.Count;

                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(listModel);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "没有出价记录";
            }
            apiContext.apiHttpResp = apiResponse;
        }



        /// <summary>
        /// 我的竞价列表
        /// </summary>
        /// <returns></returns>
        public void GetMyList(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            // 0 竞价中 2 已成交 4 已付款 6 已取消
            int order_status = dic.GetValue<int>("order_status", -10);
            int pageindex = dic.GetValue<int>("pageindex", 1);
            int pagerows = dic.GetValue<int>("pagerows", 10);

            var listModel = new MyJingjiaListModel();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            long uid = apiContext.CurrUserId;

            var jingjiaconfig = dbcontext.ADZ_JingjiaConfig.Where(t => t.is_del == 0);
            var jingjiamaster = dbcontext.ADZ_JingjiaMaster.Where(t => t.is_del == 0);
            var jingjiasubmit = dbcontext.ADZ_JingjiaSubmit.Where(t => t.uid == uid && t.is_del == 0);
            //竞价中的
            if (order_status == 0)
            {
                jingjiamaster = jingjiamaster.Where(t => t.jingjia_satus == 1);
            }
            else if (order_status == 2)
            {
                jingjiamaster = jingjiamaster.Where(t => t.jingjia_satus == 2);
                jingjiasubmit = jingjiasubmit.Where(t => t.is_hit == 1 && t.status == 2);
            }
            else if (order_status == 4)
            {
                jingjiamaster = jingjiamaster.Where(t => t.jingjia_satus == 2);
                jingjiasubmit = jingjiasubmit.Where(t => t.is_hit == 1 && t.status == 10);
            }
            else if (order_status == 6)
            {
                jingjiamaster = jingjiamaster.Where(t => t.jingjia_satus == 2);
                jingjiasubmit = jingjiasubmit.Where(t => t.is_hit == 0 || (t.is_hit == 1 && t.status == 11));
            }
            else if (order_status == -10)
            { }
            else
            {
                {
                    apiResponse.retCode = ResultEnum.NoData;
                    apiResponse.message = "参数order_status错误";
                }
                apiContext.apiHttpResp = apiResponse;
                return;
            }



            var queryable =
                from config in jingjiaconfig
                join master in jingjiamaster on config.jingjia_config_id equals master.jingjia_config_id
                join chujia in jingjiasubmit on master.jingjia_id equals chujia.jingjia_id // into temp
                //from tt in temp.DefaultIfEmpty()
                select new JingjiaModel
                {
                    jingjia_config_id = master.jingjia_config_id,
                    jingjia_id = master.jingjia_id,
                    jingjia_name = master.jingjia_name,
                    include_tax = master.include_tax,
                    base_price = master.base_price,
                    step_price = master.step_price,
                    baozheng_price = config.baozheng_price,
                    jingjia_satus = master.jingjia_satus,
                    stay_miniutes = master.stay_miniutes,
                    jingjia_type = master.jingjia_type,
                    begin_time = config.begin_time,
                    real_end_time = master.real_end_time.HasValue ? master.real_end_time : config.end_time,
                    last_time = master.last_time,
                    last_price = master.last_price,
                    last_uid = master.last_uid,
                    img_url = master.img_url,
                    is_del = master.is_del,
                    baoming_counts = config.baoming_counts,
                    chujia_counts = master.chujia_counts,
                    weiguan_counts = master.weiguan_counts,
                    remark = master.remark,
                    my_price = chujia.my_price,
                    is_baoming = 1,
                    is_hit = chujia.is_hit,
                    submit_status = chujia.status,
                    order_master_id = chujia.order_master_id,
                    submit_id = chujia.seq_id,
                    submit_time = chujia.create_time,
                    jingjia_deal_status = master.jingjia_deal_status
                };


            //数据统计
            listModel.allrows = queryable.Count();
            listModel.allpages = (listModel.allrows - 1) / pagerows + 1;

            //分页
            listModel.list = queryable.OrderByDescending(t => t.submit_id)
                .Skip(pagerows * (pageindex - 1))
                .Take(pagerows)
                .ToList();

            listModel.list.ForEach(t =>
            {
                t.order_no = "";
                if (t.last_price <= 0)
                {
                    t.last_price = t.base_price;
                }
                if (t.order_master_id > 0)
                {
                    var ordermaster = dbcontext.ADZ_OrderMaster.FirstOrDefault(o => o.order_id == t.order_master_id);
                    if (ordermaster != null)
                    {
                        t.order_no = ordermaster.order_NO;
                    }
                }
                t.img_url = SysConfigBiz.Instance.GetThingIMG(t.img_url);
            });

            if (listModel.allrows > 0)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = JsonHelper.Serialize(listModel);
            }
            else
            {
                apiResponse.retCode = ResultEnum.NoData;
                apiResponse.message = "竞价列表为空";
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 提交报名
        /// </summary>
        public void Baoming(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;
            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long jingjia_config_id = dic.GetValue<int>("jingjia_config_id", -10);
            long uid = apiContext.CurrUserId;
            Tuple<bool, string, string> result = JingjiaBiz.Instance.CreateBaoming(uid, jingjia_config_id);

            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = result.Item2;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }


        /// <summary>
        /// 支付报名订单
        /// </summary>
        /// <param name="apiContext"></param>
        public void PayBaoming(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string order_no = dic.GetValue<string>("order_no");
            string paypwd = dic.GetValue<string>("paypwd");
            int pay_type = dic.GetValue<int>("pay_type", -1);       //支付方式 2 余额 3 支付宝 4 微信
            decimal amt = dic.GetValue<decimal>("amt", 0);
            if (string.IsNullOrEmpty(order_no))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "订单号为空";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            if (amt <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "支付金额错误";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            if (!(pay_type >= 2 && EnumHelper.IsDefined<PayType>(pay_type)))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "支付方式选择错误";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            if (pay_type == (int)PayType.Balance && string.IsNullOrEmpty(paypwd))
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "请输入支付密码";
                apiContext.apiHttpResp = apiResponse;
                return;
            }

            var result = JingjiaBiz.Instance.PayBaomingOrder(apiContext.CurrUserId, paypwd, order_no, pay_type);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = result.Item2;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }



        /// <summary>
        /// 提交竞价
        /// </summary>
        /// <param name="apiContext"></param>
        public void SubmitPrice(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            long jingjia_id = dic.GetValue<int>("jingjia_id", -10);
            decimal my_price = dic.GetValue<decimal>("my_price", 0);
            if (my_price <= 0 || jingjia_id <= 0)
            {
                apiResponse.retCode = ResultEnum.ParamError;
                apiResponse.message = "参数有误，请检查后重新提交";
                apiContext.apiHttpResp = apiResponse;
                return;
            }


            var result = JingjiaBiz.Instance.JingjiaSubmt(apiContext.CurrUserId, jingjia_id, my_price);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = result.Item2;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        #region 同步两边的竞价信息

        /// <summary>
        /// 报名同步
        /// </summary>
        public void AsyncBaoming(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string username = dic.GetValue<string>("username", "");

            var result = JingjiaBiz.Instance.AsyncBaomingOrder(username);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = result.Item2;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        /// <summary>
        /// 用户报价
        /// </summary>
        /// <returns></returns>
        public void AsyncJingjiaSubmt(ApiServiceContext apiContext)
        {
            ApiHttpResponse apiResponse = new ApiHttpResponse();
            string data = apiContext.decData;

            //解密后的json字符串反序列成对象
            SortedDictionary<string, object> dic = JsonHelper.DeserializeLower(data);
            string username = dic.GetValue<string>("username", "");
            string jingjianame = dic.GetValue<string>("jingjianame", "");
            decimal my_price = dic.GetValue<decimal>("price", 0);

            var result = JingjiaBiz.Instance.AsyncJingjiaSubmt(username, jingjianame, my_price);
            if (result.Item1)
            {
                apiResponse.retCode = ResultEnum.Success;
                apiResponse.data = result.Item2;
            }
            else
            {
                apiResponse.retCode = ResultEnum.Fail;
                apiResponse.message = result.Item3;
            }
            apiContext.apiHttpResp = apiResponse;
        }

        #endregion
    }
}